import { Actions } from '@/components/Table/types';

export const getActions = (actions?: Actions): Required<Actions> => {
  const clone: Required<Actions> = {
    select: true,
    insert: true,
    update: true,
    delete: true,
    batchDelete: true,
    otherForTable: false,
    otherForRow: false,
  };
  if (actions) {
    clone.select = actions.select !== undefined ? actions.select : clone.select;
    clone.insert = actions.insert !== undefined ? actions.insert : clone.insert;
    clone.update = actions.update !== undefined ? actions.update : clone.update;
    clone.delete = actions.delete !== undefined ? actions.delete : clone.delete;
    clone.batchDelete = actions.batchDelete !== undefined ? actions.batchDelete : clone.batchDelete;
    clone.otherForTable = actions.otherForTable !== undefined ? actions.otherForTable : clone.otherForTable;
    clone.otherForRow = actions.otherForRow !== undefined ? actions.otherForRow : clone.otherForRow;
  }
  return clone;
};

/**
 * @deprecated
 **/
export const getActionsFromAccesses = (accesses: string[], tableName?: string): Required<Actions> => {
  const actions: Actions = {
    select: accesses.some(v => v === '*:select' || (tableName && v === `${tableName}:select`)),
    insert: accesses.some(v => v === '*:insert' || (tableName && v === `${tableName}:insert`)),
    delete: accesses.some(v => v === '*:delete' || (tableName && v === `${tableName}:delete`)),
    otherForTable: false,
    otherForRow: false,
  };
  actions.update = actions.insert && actions.delete;
  actions.batchDelete = actions.delete;
  return actions as Required<Actions>;
};

export const getActionsFromAuthority = (authorities: string[], tableName?: string): Required<Actions> => {
  const actions: Actions = {
    select: authorities.some(v => v === '*:select' || (tableName && v === `${tableName}:select`)),
    insert: authorities.some(v => v === '*:insert' || (tableName && v === `${tableName}:insert`)),
    delete: authorities.some(v => v === '*:delete' || (tableName && v === `${tableName}:delete`)),
    otherForTable: false,
    otherForRow: false,
  };
  actions.update = actions.insert && actions.delete;
  actions.batchDelete = actions.delete;
  return actions as Required<Actions>;
};
